<html>
<head>
<title>C++ Annotations Version 6.5.0</title>
</head>
<body text="black" bgcolor="white">
<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus09.html">Previous Chapter</a>
    <li> <a href="cplusplus11.html">Next Chapter</a>
</ul>
<hr>
<a name="StaticDataFun"></a><a name="l162"></a>
<h1>Chapter 10: Static data and functions</h1>
<a name="static"></a>
<blockquote>
    <em>
        Don't hesitate to send in feedback: send an e-mail if you like the
        C++ Annotations; if you think that important material was omitted;
        if you find errors or typos in the text or the code examples;
        or if you just feel like e-mailing. Send your e-mail to
        <a href="mailto:f.b.brokken@rug.nl">Frank B. Brokken</a>.
<p>
<strong>Please</strong> state the document version you're referring to, as found in
        the title (in this document: 6.5.0) and please state chapter and
        paragraph name or number you're referring to.
<p>
All received mail is processed conscientiously, and received
        suggestions for improvements will usually have been processed by the
        time a new version of the Annotations is released. Except for the
        incidental case I will normally not acknowledge the receipt of
        suggestions for improvements. Please don't interpret this as me not
        appreciating your efforts.
    </em>
</blockquote>
<p>
<a name="static/intro"></a>In the previous chapters we have shown examples of classes where each object
of a class had its own set of <a name="an1324"></a>
<code>public</code> or <a name="an1325"></a>
<code>private</code> data. Each <code>public</code>
or <code>private</code> member could access any member of any object of its class.
<p>
In some situations it may be desirable that one or more
    <a name="an1326"></a>
<em>common data fields</em> exist, which are accessible to <em>all</em> objects of
the class. For example, the name of the startup directory, used by
a program that recursively scans the directory tree of a disk. A second
example is a flag variable, which states whether some specific initialization
has occurred: only the first object of the class would perform the
necessary initialization and would set the flag to `done'.
<p>
Such situations are analogous to <strong>C</strong> code, where several functions need to
access the same variable. A common solution in <strong>C</strong> is to define all these
functions in one source file and to declare the variable as a <a name="an1327"></a>
<code>static</code>: the
variable name is then not known beyond the scope of the source file. This
approach is quite valid, but violates our philosophy of using only one
function per source file. Another <strong>C</strong>-solution is to give the variable in
question an unusual name, e.g., <code>_6uldv8</code>, hoping that other
program parts won't use this name by accident. Neither the first, nor the
second <strong>C</strong>-like solution is elegant.
<p>
<strong>C++</strong>'s solution is to define <a name="an1328"></a>
<code>static members</code>: data and functions, common
to all objects of a class and inaccessible outside of the class.  These static
members are the topic of this chapter.
<p>
<a name="StaticData"></a><a name="l163"></a>
<h2>10.1: Static data</h2>
    <a name="static/data"></a>Any data member of a class can be declared <code>static</code>; be it in the <code>public</code>
or <code>private</code> section of the class definition. Such a data member is created
and initialized only once, in contrast to non-static data members which are
created again and again for each separate object of the class.
<p>
<a name="an1329"></a>
 Static data members are created when the program
starts. Note, however, that they are always created as true members of
their classes. It is suggested to prefix static member names with <code>s_</code> in
order to distinguish them (in class member functions) from the class's data
members (which should preferably start with <code>d_</code>).
<p>
Public static data members <a name="an1330"></a>
 are like `normal'
<a name="an1331"></a>
global variables: they can be accessed by <em>all code of the program</em>,
simply using their class names, the scope resolution operator and their
member names.  This is illustrated in the following example:
        <pre>
    class Test
    {
        static int s_private_int;

        public:
            static int s_public_int;
    };

    int main()
    {
        Test::s_public_int = 145;   // ok

        Test::s_private_int = 12;   // wrong, don't touch
                                    // the private parts
        return 0;
    }
</pre>
    This code fragment is not suitable for consumption by a <strong>C++</strong> compiler:
it merely illustrates the <a name="an1332"></a>
<em>interface</em>, and not the <a name="an1333"></a>
<em>implementation</em> of
<code>static</code> data members, which is discussed next.
<p>
<a name="l164"></a>
<h3>10.1.1: Private static data</h3>
        <a name="static/private"></a>To illustrate the use of a static data member which is a private
variable in a class, consider the following example:
        <pre>
    class Directory
    {
        static char s_path[];

        public:
            // constructors, destructors, etc. (not shown)
    };
</pre>
    The data member <code>s_path[]</code> is a <a name="an1334"></a>
<em>private static data member</em>. During
the execution of the program, only <em>one</em> <code>Directory::s_path[]</code> exists,
even though more than one object of the class <code>Directory</code> may exist. This
data member could be inspected or altered by the constructor, destructor or by
any other member function of the class <code>Directory</code>.
<p>
Since constructors are called for each new object of a class, static
data members <a name="an1335"></a>

    <a name="an1336"></a>
 are never <em>initialized</em> by
constructors. At most they are <em>modified</em>. The reason for this is that
static data members exist <em>before</em> any constructor of the class has been
called. Static data members are initialized when they are defined, outside of
all member functions, in the same way as other global variables are
initialized.
<p>
The definition and initialization of a static data member usually occurs
in one of the source files of the class functions, preferably in a source file
dedicated to the definition of static data members, called <a name="an1337"></a>
<code>data.cc</code>.
<p>
The data member <code>s_path[]</code>, used above, could thus be
defined and initialized as follows in a file <code>data.cc</code>:
        <pre>
    include "directory.ih"

    char Directory::s_path[200] = "/usr/local";
</pre>
    In the class interface the static member is actually only <em>declared</em>. In
its implementation (definition) its type and class name are explicitly
mentioned. Note also that the <a name="an1338"></a>
size specification can be left out of the
interface, as shown above. However, its size <em>is</em> (either explicitly or
implicitly) required when it is defined.
<p>
Note that <em>any</em> source file could contain the definition of the static
data members of a class. A separate <code>data.cc</code> source is advised, but the
source file containing, e.g., <code>main()</code> could be used as well. Of course, any
source file defining static data of a class must also include the header
file of that class, in order for the static data member to be known to the
compiler.
<p>
A second example of a useful private static data member is given below. Assume
that a class <code>Graphics</code> defines the communication of a program with a
graphics-capable device (e.g., a VGA screen). The initialization of the
device, which in this case would be to switch from text mode to graphics mode,
is an action of the constructor and depends on a <code>static</code> flag variable
<code>s_nobjects</code>. The variable <code>s_nobjects</code> simply counts the number of
<code>Graphics</code> objects which are present at one time. Similarly, the destructor
of the class may switch back from graphics mode to text mode when the last
<code>Graphics</code> object ceases to exist.  The class interface for this
<code>Graphics</code> class might be:
        <pre>
    class Graphics
    {
        static int s_nobjects;              // counts # of objects

        public:
            Graphics();
            ~Graphics();                    // other members not shown.
        private:
            void setgraphicsmode();         // switch to graphics mode
            void settextmode();             // switch to text-mode
    }
</pre>
    The purpose of the variable <code>s_nobjects</code> is to count the number of
objects existing at a particular moment in time. When the first object is
created, the graphics device is initialized. At the destruction of the last
<code>Graphics</code> object, the switch from graphics mode to text mode is made:
        <pre>
    int Graphics::s_nobjects = 0;           // the static data member

    Graphics::Graphics()
    {
        if (!s_nobjects++)
            setgraphicsmode();
    }

    Graphics::~Graphics()
    {
        if (!--s_nobjects)
            settextmode();
    }
</pre>
    Obviously, when the class <code>Graphics</code> would define more than one
constructor, each constructor would need to increase the variable
<code>s_nobjects</code> and would possibly have to initialize the graphics mode.
<p>
<a name="l165"></a>
<h3>10.1.2: Public static data</h3>
        <a name="static/public"></a>Data members can be declared in the <a name="an1339"></a>
public section of a class,
although this is not common practice (as this would violate the principle
of <a name="an1340"></a>
data hiding). E.g., when the static data member <code>s_path[]</code> from
section <a href="cplusplus10.html#StaticData">10.1</a> would be declared in the public section of
the class definition, all program code could access this variable:
        <pre>
    int main()
    {
        getcwd(Directory::s_path, 199);
    }
</pre>
    Note that the variable <code>s_path</code> would still have to be defined. As
before, the class interface would only <em>declare</em> the array <code>s_path[]</code>.
This means that some source file would still need to contain the definition of
the <code>s_path[]</code> array.
<p>
<a name="l166"></a>
<h3>10.1.3: Initializing static const data</h3>
        <a name="static/const"></a>Static <code>const</code> <a name="an1341"></a>
 data members may be
initialized in the class interface if these data members are of an integral
data type. So, in the following example the first three static data members
can be initialized since <code>int</code> <code>enum</code> and <code>double</code> types are integral
data members. The last static data member cannot be initialized in the class
interface since <code>string</code> is not an integral data type:
        <pre>
    class X
    {
        public:
            enum Enum
            {
                FIRST,
            };

            static int const s_x = 34;
            static Enum const s_type = FIRST;

            static double const s_d = 1.2;
            static string const s_str = "a";    // won't compile
    };
</pre>
    Static <code>const</code> integral data members initialized in the class interface
are not <a name="an1342"></a>
addressable variables. They are mere symbolic names for their
associated values. Since they are not variables, it is not possible to
determine their addresses. Note that this is not a compilation problem, but a
linking problem. The static <code>const</code> variable that is initialized in the
class interface does not exist as an addressable entity.
<p>
A statement like <code>int *ip = &amp;X::s_x</code> will therefore <em>compile</em>
correctly, but will fail to <em>link</em>.  Static variables that are explicitly
defined in a source file <em>can</em> be linked correctly, though. So, in the
following example the address of <code>X::s_x</code> cannot be solved by the linker,
but the address of <code>X::s_y</code> <em>can</em> be solved by the linker:
        <pre>
    class X
    {
        public:
            static int const s_x = 34;
            static int const s_y;
    };

    int const X::s_y = 12;

    int main()
    {
        int const *ip = &amp;X::s_x;    // compiles, but fails to link
        ip = &amp;X::s_y;               // compiles and links correctly
    }
</pre>
<p>
<a name="l167"></a>
<h2>10.2: Static member functions</h2>
    <a name="static/function"></a>Besides static data members, <strong>C++</strong> allows the definition of
    <a name="an1343"></a>
<em>static member functions</em>. Similar to the concept of static data, in
which these variables are shared by all objects of the class, static
member functions exist without any associated object of their class.
<p>
Static member functions <a name="an1344"></a>

    <a name="an1345"></a>
 can access all static members of their class,
but <em>also</em> the members (<code>private</code> or <code>public</code>) of objects of their class
<em>if</em> they are informed about the existence of these objects, as in the
upcoming example. Static member functions are themselves not associated with
any object of their class. Consequently, they do not have a <a name="an1346"></a>
<code>this</code>
pointer. In fact, a static member function is completely comparable to a
<a name="an1347"></a>
global function, not associated with any class (i.e., in practice they
are. See the next section (<a href="cplusplus10.html#CALLINGCONVENTION">10.2.1</a>) for a subtle note). Since
static member functions do not require an associated object,
static
member functions declared in the public section of a class
interface may be called without specifying an object of its class.  The
following example illustrates this characteristic of static member
functions:
        <pre>
    class Directory
    {
        string d_currentPath;
        static char s_path[];

        public:
            static void setpath(char const *newpath);
            static void preset(Directory &amp;dir, char const *path);
    };
    inline void Directory::preset(Directory &amp;dir, char const *newpath)
    {
                                                    // see the text below
        dir.d_currentPath = newpath;                // 1
    }

    char Directory::s_path[200] = "/usr/local";     // 2

    void Directory::setpath(char const *newpath)
    {
        if (strlen(newpath) &gt;= 200)
            throw "newpath too long";

        strcpy(s_path, newpath);                    // 3
    }

    int main()
    {
        Directory dir;

        Directory::setpath("/etc");                 // 4
        dir.setpath("/etc");                        // 5

        Directory::preset(dir, "/usr/local/bin");   // 6
        dir.preset(dir, "/usr/local/bin");          // 7
    }
</pre>
    <ul>
    <li> at 1 a static member function modifies a <a name="an1348"></a>
private data member
of an object. However, the object whose member must be modified is given to
the member function as a reference parameter.
<p>
Note that <a name="an1349"></a>

    <a name="an1350"></a>
 static member functions can be defined
as <a name="an1351"></a>
inline functions.
    <li> at 2 a relatively long array is defined to be able to accomodate
long paths. Alternatively, a <code>string</code> or a pointer to dynamic memory could
have been used.
    <li> at 3 a (possibly longer, but not too long) new pathname is stored in
the static data member <code>s_path[]</code>. Note that here only static members
are used.
    <li> at 4, <code>setpath()</code> is called. It is a static member, so no
object is required. But the compiler must know to which class the function
belongs, so the class is mentioned, using the <a name="an1352"></a>
scope resolution operator.
    <li> at 5, the same is realized as in 4. But here <code>dir</code> is used to tell
the compiler that we're talking about a function in the <code>Directory</code>
class. So, static member functions <em>can</em> be called as normal member
functions.
    <li> at 6, the <code>currentPath</code> member of <code>dir</code> is altered. As in 4, the
class and the scope resolution operator are used.
    <li> at 7, the same is realized as in 6. But here <code>dir</code> is used to tell
the compiler that we're talking about a function in the <code>Directory</code>
class. Here in particular note that this is <em>not</em> using <code>preset()</code> as an
ordinary member function of <code>dir</code>: the function still has no
<a name="an1353"></a>
<code>this</code>-pointer, so <code>dir</code> must be passed as argument to inform the
static member function <code>preset</code> about the object whose <code>currentPath</code>
member it should modify.
    </ul>
<p>
In the example only public static member functions were used.  <strong>C++</strong>
also allows the definition of private static member functions: these functions
can only be called by member functions of their class.
<p>
<a name="CALLINGCONVENTION"></a><a name="l168"></a>
<h3>10.2.1: Calling conventions</h3>
        <a name="static/calling"></a>    As noted in the previous section, static (public) member functions are
comparable to classless functions. However, formally this statement is not
true, as the <strong>C++</strong> standard does not prescribe the same calling conventions
for static member functions and for classless global functions.
<p>
In practice these calling conventions are identical, implying that the
address of a static member function could be used as an argument in functions
having parameters that are
    <a name="an1354"></a>
 pointers to (global) functions.
<p>
If unpleasant surprises must be avoided at all cost, it is suggested to
create global classless <a name="an1355"></a>
<em>wrapper functions</em> around static member functions
that must be used as <a name="an1356"></a>
<em>call back</em> functions for other functions.
<p>
Recognizing that the traditional situations in which call back functions
are used in <strong>C</strong> are tackled in <strong>C++</strong> using template algorithms
(cf. chapter <a href="cplusplus17.html#STL">17</a>), let's assume that we have a class <code>Person</code> having
data members representing the person's name, address, phone and
weight. Furthermore, assume we want to sort an array of pointers to <code>Person</code>
objects, by comparing the <code>Person</code> objects these pointers point to. To keep
things simple, we assume that a public static
        <pre>
    int Person::compare(Person const *const *p1, Person const *const *p2);
</pre>
    exists. A useful characteristic of this member is that it may directly
inspect the required data members of the two <code>Person</code> objects passed to the
member function using double pointers.
<p>
Most compilers will allow us to pass this function's address as the
address of the comparison function for the standard <strong>C</strong> <a name="an1357"></a>
<code>qsort()</code>
function. E.g.,
        <pre>
    qsort
    (
        personArray, nPersons, sizeof(Person *),
        reinterpret_cast&lt;int(*)(const void *, const void *)&gt;(Person::compare)
    );
</pre>
    However, if the compiler uses different calling conventions for static
members and for classless functions, this might not work. In such a case, a
classless wrapper function like the following may be used profitably:
        <pre>
    int compareWrapper(void const *p1, void const *p2)
    {
        return
            Person::compare
            (
                reinterpret_cast&lt;Person const *const *&gt;(p1),
                reinterpret_cast&lt;Person const *const *&gt;(p2)
            );
    }
</pre>
    resulting in the following call of the <code>qsort()</code> function:
        <pre>
    qsort(personArray, nPersons, sizeof(Person *), compareWrapper);
</pre>
    Note:
    <ul>
    <li> The wrapper function takes care of any mismatch in the calling
conventions of static member functions and classless functions;
    <li> The wrapper function handles the required type casts;
    <li> The wrapper function might perform small additional services (like
dereferencing pointers if the static member function expects references to
<code>Person</code> objects rather than double pointers);
    <li> As noted before: in current <strong>C++</strong> programs functions like
<code>qsort()</code>, requiring the specification of call back functions are seldomly
used, in favor of existing generic template algorithms (cf. chapter <a href="cplusplus17.html#STL">17</a>).
    </ul>
<p>

<hr>
<ul>
    <li> <a href="cplusplus.html">Table of Contents</a>
    <li> <a href="cplusplus09.html">Previous Chapter</a>
    <li> <a href="cplusplus11.html">Next Chapter</a>
</ul>
<hr>
</body>
</html>
